package com.JavaNet.chapter04_INetAddress;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;

/**
 * @author SwordFall
 * date 2017-12-03 16:07.
 * desc : *
 * final类
 * 父类为InetAddress
 * Inet4Address Internet Protocol version 4 (IPv4) 地址。
 * 为了区分IPv4和IPv6地址,Java提供了两个类:Inet4Address和Inet6Address,它们都是InetAddress类的子类
 * 当使用InetAddress类的四个静态方法创建InetAddress对象后，可以通过getAddress返回的byte数组来判断这个IP地址是IPv4还是IPv6地址
 * （byte数组长度为4就是IPv4地址，byte数组长度为16就是IPv6地址），
 * 也可以将instanceof来确定InetAddress对象是它的哪个子类的实例
 **/
public class INet4AddressDemo {


    public static void showProperties() throws UnknownHostException {

        InetAddress inetAddress = Inet4Address.getLocalHost();

        System.out.println(inetAddress.toString());

        System.out.println(inetAddress.getHostAddress());
        System.out.println(inetAddress.getCanonicalHostName());
        System.out.println(inetAddress.getHostName());
        byte[] bytes = inetAddress.getAddress();
        System.out.println(Arrays.toString(bytes));
    }

    public static void isIpV4() throws UnknownHostException {
        String website = "www.google.com";
        // String website="www.neu6.edu.cn";

        InetAddress address = InetAddress.getByName(website);
        System.out.println("IP:" + address.getHostAddress());
        switch (address.getAddress().length) {
            case 4:
                System.out.println("根据byte数组长度判断这个IP地址是IPv4地址!");
                break;
            case 6:
                System.out.println("根据byte数组长度判断这个IP地址是IPv6地址!");
                break;
        }
        if (address instanceof Inet4Address) {
            System.out.println("使用instanceof判断这个IP地址是IPv4地址!");
        } else if (address instanceof Inet6Address) {
            System.out.println("使用instanceof判断这个IP地址是IPv6地址!");
        }


        address = Inet4Address.getByAddress(new byte[]{74, 86, 118, 24});

        System.out.println("通过IP获取的主机地址: " + address.getHostName());
    }


    public static void main(String[] args) throws Exception {
        showProperties();
        isIpV4();

    }
}
